import {
  CanActivate,
  ExecutionContext,
  HttpException,
  Injectable,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';

declare module 'express' {
  interface Request {
    user?: {
      id: number;
      username: string;
    };
  }
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const requset: Request = context.switchToHttp().getRequest();

    const token = requset.headers.authorization;
    try {
      const res = this.jwtService.verify(token, { secret: 'nest@' });
      console.log(res);
      requset.user = res;
    } catch (error) {
      throw new HttpException('登录失效，请重新登录', 401);
    }

    return true;
  }
}
